package com.qf.fmall2204.index.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2204.index.entity.Category;
import com.qf.fmall2204.index.mapper.CategoryMapper;
import com.qf.fmall2204.index.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2204.product.entity.Product;
import com.qf.fmall2204.product.mapper.ProductMapper;
import com.qf.fmall2204.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author dong
 * @since 2023-04-21
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ProductMapper productMapper;

    @Autowired
    IProductService productService;

    @Override
    public List<Category> categoryListBySql() {

        CategoryMapper categoryMapper = this.getBaseMapper();

        List<Category> data = categoryMapper.categoryListBySql();

        return data;
    }


    @Override
    public List<Category> categoryListByMP() {

        //1. 查询所有一级分类信息
        // SELECT * FROM category WHERE parent_id=0;
        List<Category> firstCategories = this.list(new QueryWrapper<Category>().eq("parent_id", 0));

        //2. 遍历 所有一级分类，根据每个一级分类的 id 查询他的下级分类
        for (Category firstCategory : firstCategories) {

            // SELECT * FROM category WHERE parent_id=firstCategory.getCategoryId;
            Integer categoryId = firstCategory.getCategoryId();
            List<Category> secondCategories = this.list(new QueryWrapper<Category>().eq("parent_id", categoryId));

            // 遍历二级分类，查询三级分类
            for (Category secondCategory : secondCategories) {

                Integer secondId = secondCategory.getCategoryId();

                List<Category> thirdCategories = this.list(new QueryWrapper<Category>().eq("parent_id", secondId));

                // 给二级分类的categories属性赋值
                secondCategory.setCategories(thirdCategories);
            }

            // 给一级分类的 categories属性赋值
            firstCategory.setCategories(secondCategories);
        }

        return firstCategories;
    }

    @Override
    public List<Category> categoryListByMPBetter() {

        //1. 把所有的分类信息查询出来
        List<Category> allCategories = this.list();

        //2. 获取 一级分类信息
        ArrayList<Category> firstCategories = new ArrayList<>();
        for (Category category : allCategories) {
            Integer parentId = category.getParentId();
            if (parentId.equals(0)){
                firstCategories.add(category); // 添加一级分类
            }
        }

        //3. 遍历 firstCategories ，为每个一级分类填充 二级分类
        for (Category firstCategory : firstCategories) {
            Integer firstId = firstCategory.getCategoryId();
            ArrayList<Category> secondCategories = new ArrayList<>();
            // 从allCategories中查找当前一级分类对应的二级分类
            for (Category category : allCategories) {
                if (category.getParentId().equals(firstId)){
                    secondCategories.add(category); // 添加二级分类
                }
            }
            firstCategory.setCategories(secondCategories);

            // 为二级分类 填充三级分类
            for (Category secondCategory : secondCategories) {
                Integer secondId = secondCategory.getCategoryId();
                ArrayList<Category> thirdCategories = new ArrayList<>();
                for (Category category : allCategories) {

                    if (category.getParentId().equals(secondId)){
                        thirdCategories.add(category); // 添加三级分类
                    }

                }
                secondCategory.setCategories(thirdCategories);
            }
        }



        return firstCategories;
    }

    @Override
    public List<Category> categoryListByMPStream() {

        //1. 把所有的分类信息查询出来
        List<Category> allCategories = this.list();

        // 需要的数据结构
        // map : key=parentid ,  value= List<Category>
        Map<Integer, List<Category>> map = allCategories.stream().collect(Collectors.groupingBy(new Function<Category, Integer>() {
            @Override
            public Integer apply(Category category) {
                return category.getParentId();
            }
        }));

//        Map<Integer, List<Category>> map = allCategories.stream().collect(Collectors.groupingBy(category -> category.getParentId()));
//        Map<Integer, List<Category>> map = allCategories.stream().collect(Collectors.groupingBy(Category::getParentId));

        //2. 获取一级分类数据
        List<Category> firstCategories = map.get(0);

        for (Category firstCategory : firstCategories) {

            Integer firstId = firstCategory.getCategoryId();

            List<Category> secondCategories = map.get(firstId);

            firstCategory.setCategories(secondCategories);

            for (Category secondCategory : secondCategories) {
                Integer secondId = secondCategory.getCategoryId();
                List<Category> thirdCategories = map.get(secondId);
                secondCategory.setCategories(thirdCategories);
            }
        }


        return firstCategories;
    }

    @Override
    public List<Category> categoryRecommends() {

        //1. 查询所有一级分类信息
        List<Category> categories = this.list(new QueryWrapper<Category>().eq("parent_id", 0));

        //2. 给每个一级分类信息查询下属的销量前六的商品信息
        for (Category category : categories) {
            Integer categoryId = category.getCategoryId();
            List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().eq("root_category_id", categoryId)
                    .orderByDesc("sold_num").last("limit 6"));

            if (productList!=null&&productList.size()>0){
                // 填充商品图片信息
                productService.populateProductImg(productList);
            }

            // 设置商品信息到当前的分类对象中
            category.setProducts(productList);
        }

        return categories;
    }

    @Override
    public List<Category> categoryRecommendsBetter() {

        //1. 查询所有一级分类信息
        List<Category> categories = this.list(new QueryWrapper<Category>().eq("parent_id", 0));

        //2. 查询一级分类下的所有商品信息
        // List<Category> ===> List<CategoryId>
        List<Integer> categoryIdList = categories.stream().map(Category::getCategoryId).collect(Collectors.toList());

        // SELECT * FROM product WHERE root_category_id IN (1,2,3);
        List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().in("root_category_id", categoryIdList));

        //3. 数据处理
        // 需要一个Map， key=大类的ID，value=List<这个大类下的商品>
        Map<Integer, List<Product>> productMap = productList.stream().collect(Collectors.groupingBy(Product::getRootCategoryId));

        // 遍历所有一级分类，设置products属性
        for (Category category : categories) {
            Integer categoryId = category.getCategoryId();
            List<Product> products = productMap.get(categoryId); // 该大类下的商品信息
            if (products==null){
                category.setProducts(new ArrayList<Product>()); // 避免前端js报错
            }else {
                // 取销量前六的商品
//                products.sort(new Comparator<Product>() {
//                    @Override
//                    public int compare(Product o1, Product o2) {
//                        return o1.getSoldNum()-o2.getSoldNum();
//                    }
//                });
                List<Product> sortedProducts = products.stream()
                        .sorted((o1, o2) -> o2.getSoldNum().compareTo(o1.getSoldNum()))
                        .limit(6)
                        .collect(Collectors.toList());


                // 填充商品的图片信息
                productService.populateProductImg(sortedProducts);
                category.setProducts(sortedProducts);
            }

        }


        return categories;
    }
}
